package com.cefa.edu.service;

import com.cefa.edu.dao.*;
import com.cefa.edu.model.*;
import com.cefa.edu.pojo.OrganRelation;
import com.cefa.edu.pojo.Phase;
import com.cefa.edu.pojo.UserOrganRole;
import com.cefa.edu.util.MD5Generator;
import org.apache.ibatis.transaction.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author huangzehui
 * @date 18-7-30 上午9:13
 */
@Service
public class EducationLevelService {
    @Autowired
    EducationLevelMapper educationLevelMapper;

    @Autowired
    UserMapper userMapper;
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    ScoreMapper scoreMapper;

    @Autowired
    ClassMapper classMapper;
    @Autowired
    PhaseMapper phaseMapper;
    @Autowired
    GradeMapper gradeMapper;
    @Autowired
    OrganRelationMapper organRelationMapper;
    @Autowired
    UserOrganRoleMapper userOrganRoleMapper;
//    @Transactional("transactionManager")
//    public void insertEducationLevel(EducationLevel educationLevel,Integer  userId,Integer roleType,String names) {
//        //添加阶层时，需额外添加客户与阶层的关系,admin用户如果不是添加第一层，其他的都没必要关联
//        educationLevelMapper.insertEducationLevel(educationLevel);
//        //如果保存的是教育阶段，自动生成年级数据
//        if(educationLevel.getLevel()==1){
//            String [] args =names.split(",");
//            int correntYear = Calendar.getInstance().get(Calendar.YEAR);//当前年
//            for (int i=0;i<args.length;i++){
//                EducationLevel educationLevel1= new EducationLevel();
//                educationLevel1.setSort(i+1);
//                educationLevel1.setGradeDate(correntYear-i+"");
//                educationLevel1.setSchoolId(educationLevel.getSchoolId());
//                educationLevel1.setPId(educationLevel.getId());
//                educationLevel1.setName(args[i]);
//                educationLevel1.setLevel(2);
//                educationLevel1.setGId(0);
//                educationLevelMapper.insertEducationLevel(educationLevel1);
//            }
//        }
//        List<User> userList=userMapper.getUserRole(userId,"asc");
//        if(userList!=null&&!userList.isEmpty()){
//            if(("admin".equals(userList.get(0).getUserName())&&educationLevel.getLevel()==1)||!"admin".equals(userList.get(0).getUserName())){
//                userMapper.insertUserLevel(userId,educationLevel.getId(),roleType,userList.get(0).getSchoolId(),null,0);
//            }
//        }
//    }
    @Transactional("transactionManager")
    public  void  deleteUserEducationLevel(Integer userId,Integer levelId,Integer roleType,Integer instructorId) {
        Role role = userMapper.getRoleByType(roleType);
        //1、如果删除的是管理者，则只需要删除用户和层级的关联表数据即可
        //2、如果是任课老师（包括班主任），则需要删除任课老师表，根据level_id和user_id查询出一条，则还需要删除用户和层级的关联表，如果大于1条（说明该老师任课多门课程或者还是班主任），那么就不能删除用户和层级的关联数据表
        if("manager".equals(role.getRoleName())){//管理者
            educationLevelMapper.deleteUserEducationLevelByUserId(userId,levelId);
        }else if("director".equals(role.getRoleName())||"instructor".equals(role.getRoleName())){//老师
            int count=userMapper.getInstructor(userId,levelId);
            if(count<=1){//如果等于1条（最少只能有一条）则需要额外删除用户和层级的关联数据表,如果等于2说明不仅是任课老师还是班主任，两条数据就不能删除用户和老师的级联关系
                educationLevelMapper.deleteUserEducationLevelByUserId(userId,levelId);
                educationLevelMapper.deleteInstructor(instructorId);
            }else{
                educationLevelMapper.deleteInstructor(instructorId);
            }
        }else if("student".equals(role.getRoleName())){//
            educationLevelMapper.deleteUserEducationLevelByUserId(userId,levelId);
        }
//       else if("guardian".equals(role.getRoleName())){//监护人暂时不提供入口
//
//        }
    }

    @Transactional("transactionManager")
    public int  getUserLevel(Integer userId ,Integer levelId) {
        return  educationLevelMapper.getUserLevel(userId,levelId);
    }

    @Transactional("transactionManager")
    public int  updateLevelPid(Integer levelId,Integer pId) {
        return  educationLevelMapper.updateLevelPid(levelId,pId);
    }
    @Transactional("transactionManager")
    public List<EducationLevel>  getEducationLevel(Integer userId,Integer level) {
        return  educationLevelMapper.getEducationLevel(userId,level);
    }

    @Transactional("transactionManager")
    public List<EducationLevel>  getEducationLevelByuserIdAndpId(Integer userId,Integer levelId) {
        return  educationLevelMapper.getEducationLevelByuserIdAndpId(userId,levelId);
    }

    @Transactional("transactionManager")
    public List<ScoreInfo>  studentChainData(Integer userId,Integer roleType,Integer chainStatus) {
        //1、判断角色
        //2、如果是admin用户，则查询所有的成绩（在校生成绩）g_id in(所有的教育阶段)
        //3、如果是管理者 分为1层管理者和2成管理者，如果都有，则 把一层管理者的层id查询出来，再把二层的管理者的层id查出来  用 p_id in() g_id in()
        //4、如果时老师或班主任 根据userId 和user_level 表连查，
        //5如果是监护人和学生，则根据学生的id查询成绩表
        List<ScoreInfo> list=null;
        if(roleType==1){//admin
            List<EducationLevel> educationLevelList= educationLevelMapper.getEducationLevel(userId, 1);
            String ids="";
            for (int i=0;i<educationLevelList.size();i++){
                if(ids.length()==0){
                    ids=ids+educationLevelList.get(i).getId();
                }else{
                    ids=ids+","+educationLevelList.get(i).getId();
                }
            }
            list= scoreMapper.studentChainData(ids,chainStatus);
        }else if(roleType==2){//管理者
            List<EducationLevel> educationLevelList= educationLevelMapper.getEducationLevel(userId, 1);
            String gids="";
            String pids="";
            String ids="";
            for (int i=0;i<educationLevelList.size();i++){
                if(gids.length()==0){
                    gids=gids+educationLevelList.get(i).getId();
                }else{
                    gids=gids+","+educationLevelList.get(i).getId();
                }
            }
            List<EducationLevel> educationLevelList2= educationLevelMapper.getEducationLevel(userId, 2);

            for (int i=0;i<educationLevelList2.size();i++){
                if(pids.length()==0){
                    pids=pids+educationLevelList2.get(i).getId();
                }else{
                    pids=pids+","+educationLevelList2.get(i).getId();
                }
            }
            List<EducationLevel> educationLevelList3=null;
            int status=0;
            int state=0;
            if(gids.length()>0&&pids.length()>0){//同时是一层管理者和二层管理者
                status=1;
                educationLevelList3=educationLevelMapper.getEducationLevelByIdAndPidNotIn(userId,3,gids,pids);
            }else if(gids.length()==0&&pids.length()>0){//只是二层管理者
                status=2;
                educationLevelList3=educationLevelMapper.getEducationLevelByIdNotIn(userId,3,pids);
            }else if(gids.length()>0&&pids.length()==0){//只是一层管理者(或者二层管理者但是二层在一级管理者的范围内)
                status=3;
                educationLevelList3=educationLevelMapper.getEducationLevelByPidNotIn(userId,3,gids);//对只是班主任来、老师来说，他们是在三层有权限
            }else if(gids.length()==0&&pids.length()==0){//不是管理者
                status=4;
                educationLevelList3=educationLevelMapper.getEducationLevel(userId,3);
            }
            if(educationLevelList3!=null&&educationLevelList3.size()>0){
                for (EducationLevel educationLevel :educationLevelList3){
                    if(ids.length()==0){
                        ids=ids+educationLevel.getId();
                    }else{
                        ids=ids+","+educationLevel.getId();
                    }
                }
            }
            //1、根据userId和ids查询出该用户的老师（班主任）信息列表
            //2、把查询的列表里的courseid 放到一个list中
            //3、把course_id 是空的全部单独放起来 和不为空的形成or条件，为空的查询该班级的所有学生成绩 or 不为空的查询该班级下的课程下的学生成绩
            List<Instructor> instructorList=new ArrayList<Instructor>();
            if(ids.length()>0){
                instructorList=userMapper.findInstructorAndUserByLevelId(ids);//如果ids有值，则一定能查询出来数据
                state=1;
            }
            String courseIds="";
            String levelIds="";
            Integer levelCount=0;
            for(Instructor instructor : instructorList){
                if(instructor.getCourseId()==null){
                    levelIds=levelIds+","+instructor.getLevelId();
                    levelCount++;
                }else{
                    courseIds=courseIds+","+instructor.getCourseId();
                }
            }
            if(levelIds.length()>0){
                levelIds=levelIds.substring(1,levelIds.length());
            }
            if(courseIds.length()>0){
                courseIds=courseIds.substring(1,courseIds.length());
            }
            if(gids.length()>0||pids.length()>0||ids.length()>0){
                list=scoreMapper.getScoreByids(status,state,levelIds.length()>0?levelIds:null,courseIds.length()>0?courseIds:null,pids,gids,chainStatus,levelCount);
            }
        }else if(roleType==3||roleType==4){//老师(任课老师只能查看所教的课程成绩，班主任可以查看全班级的所有学生成绩)
            List<EducationLevel> educationLevelList= educationLevelMapper.getEducationLevelByUserId(userId);
            String ids="";
            for(EducationLevel educationLevel:educationLevelList){
                ids=ids+","+educationLevel.getId();
            }
            if(ids.length()>0){
                ids=ids.substring(1,ids.length());
            }
            List<Instructor> instructorList=new ArrayList<Instructor>();
            if(ids.length()>0){
                instructorList=userMapper.findInstructorAndUserByLevelId(ids);//如果ids有值，则一定能查询出来数据
            }
            String courseIds="";
            String levelIds="";
            Integer levelCount=0;
            for(Instructor instructor : instructorList){
                if(instructor.getCourseId()==null){//如果是班主任，对整个该层level都有权限
                    levelCount++;
                    levelIds=levelIds+","+instructor.getLevelId();
                }else{
                    courseIds=courseIds+","+instructor.getCourseId();//如果时老师，只会对该们课程有权限
                }
            }
            if(levelIds.length()>0){//班主任所管理的班级（可以是多个班级的班主任）
                levelIds=levelIds.substring(1,levelIds.length());
            }
            if(courseIds.length()>0){//任课老师所在的层级（一个老师可能在多个班级教课）
                courseIds=courseIds.substring(1,courseIds.length());
            }
            list= scoreMapper.getScoreByids2(levelIds,courseIds.length()>0?courseIds:null,chainStatus,levelCount);
        }else if(roleType==5){//监护人
            com.cefa.edu.pojo.User user =userMapper.getUserById(userId);
            list=scoreMapper.getScoreInfoByUserId2(user.getId(),chainStatus);
        }else if(roleType==6){
            com.cefa.edu.pojo.User user =userMapper.getUserById(userId);
            list=scoreMapper.getScoreInfoByUserId2(user.getStudentId(),chainStatus);
        }
        return  list;
    }

    @Transactional("transactionManager")
    public int  getEducationLevelByLevelAndName(Integer level,String name) {
        return educationLevelMapper.getEducationLevelByLevelAndName(level,name);
    }

    //---------------------------------------------------------------------------



}
